package com.example.androidlearning.sy10.sy2sqlite;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.androidlearning.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Sy1002_MainSQLite extends AppCompatActivity {

    MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sy1002_sqlite);
        setTitle(R.string.test2_name);

        // 创建MyDatabaseHelper对象，指定数据库版本为1，此处使用相对路径即可
        // 数据库文件自动会保存在程序的数据文件夹的databases目录下
        dbHelper = new MyDatabaseHelper(this, "myDict.db3", 7);

        Button saveInfoBtn = findViewById(R.id.saveInfoBtn);
        saveInfoBtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                String account = ((EditText) findViewById(R.id.accountText)).getText().toString();
                if (account.equals("")) {
                    Toast.makeText(v.getContext(), "账号为必填项", Toast.LENGTH_SHORT).show();
                    return;
                }
                Cursor cursor = dbHelper.getReadableDatabase()
                        .rawQuery("SELECT _account FROM user_info WHERE _account = ?"
                                , new String[]{account});
                if (cursor.getCount() > 0) {
                    Toast.makeText(v.getContext(), "此账号已存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                insertData(dbHelper.getReadableDatabase(), getUserInput());
                Toast.makeText(v.getContext(), "保存成功", Toast.LENGTH_SHORT).show();
            }
        });

        Button clearInfoBtn = findViewById(R.id.clearInfoBtn);
        clearInfoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((EditText) findViewById(R.id.accountText)).setText("");
                ((EditText) findViewById(R.id.passwordText)).setText("");
                ((EditText) findViewById(R.id.nameText_2)).setText("");
                ((EditText) findViewById(R.id.emailText)).setText("");
                ((EditText) findViewById(R.id.telText)).setText("");
                ((EditText) findViewById(R.id.workText)).setText("");
                Toast.makeText(v.getContext(), "已清空", Toast.LENGTH_SHORT).show();
            }
        });

        Button displayInfoBtn = findViewById(R.id.displayInfoBtn);
        displayInfoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor cursor = dbHelper.getReadableDatabase()
                        .rawQuery("select * from user_info", new String[]{});
                // 创建一个Bundle对象
                Bundle data = new Bundle();
                data.putSerializable("data", converCursorToList(cursor));
                // 创建一个Intent
                Intent intent = new Intent(Sy1002_MainSQLite.this, Sy1002_ResultActivity.class);
                intent.putExtras(data);
                Toast.makeText(v.getContext(), "进入显示界面", Toast.LENGTH_SHORT).show();
                // 启动Activity
                startActivity(intent);
            }
        });
    }

    private Map<String, Object> getUserInput() {
        String account = ((EditText) findViewById(R.id.accountText)).getText().toString();
        String password = ((EditText) findViewById(R.id.passwordText)).getText().toString();
        String name = ((EditText) findViewById(R.id.nameText_2)).getText().toString();
        String email = ((EditText) findViewById(R.id.emailText)).getText().toString();
        String tel = ((EditText) findViewById(R.id.telText)).getText().toString();
        String work = ((EditText) findViewById(R.id.workText)).getText().toString();

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("account", account);
        userInfo.put("password", password);
        userInfo.put("name", name);
        userInfo.put("email", email);
        userInfo.put("tel", tel);
        userInfo.put("work", work);

        return userInfo;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void insertData(SQLiteDatabase db, Map<String, Object> userInfo) {
        // 执行插入语句
        db.execSQL("insert into user_info values(? , ? , ?, ? , ? , ?)"
                , new String[]{
                        Objects.requireNonNull(userInfo.get("account")).toString(),
                        Objects.requireNonNull(userInfo.get("password")).toString(),
                        Objects.requireNonNull(userInfo.get("name")).toString(),
                        Objects.requireNonNull(userInfo.get("email")).toString(),
                        Objects.requireNonNull(userInfo.get("tel")).toString(),
                        Objects.requireNonNull(userInfo.get("work")).toString()
                });
    }

    public static ArrayList<Map<String, String>> converCursorToList(Cursor cursor) {
        ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
        // 遍历Cursor结果集
        while (cursor.moveToNext()) {
            // 将结果集中的数据存入ArrayList中
            Map<String, String> map = new HashMap<>();
            // 取出查询记录中除了密码列的值
            map.put("account", cursor.getString(0));
            map.put("name", cursor.getString(2));
            map.put("email", cursor.getString(3));
            map.put("tel", cursor.getString(4));
            map.put("work", cursor.getString(5));
            result.add(map);
        }
        return result;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }
}
